import { computed, ref, unref } from 'vue'
import { useDebounceFn } from '@vueuse/core';

// 封装列表请求
export function useList({ url, immediate = true }) {
  // 查询条件
  const searchForm = ref({})

  // 分页
  const page = ref({
    pageSize: 20,
    pageNum: 1,
    total: 0,
  })

  // loading
  const tableLoading = ref(false)
  // 返回数据
  const tableData = ref([])

  const reset = () => {
    page.value.pageNum = 1
    searchForm.value = {}
    loadList()
  }

  const queryPage = useDebounceFn(() => {
    loadList()
  }, 300)

  immediate && loadList()

  async function loadList() {
    tableLoading.value = true;
    const data = await apis.getList({ ...page.value, ...searchForm.value });
    tableLoading.value = false;
    if (data) {
      page.value.total = data.total ? data.total : 0;
      tableData.value = data.list ? data.list : [];
    }
  }

  // 新增/编辑弹窗
  const formVisible = ref(false);
  const formData = ref({});
  function showForm(item = {}) {
    formData.value = { ...item };
    formVisible.value = true;
  }
  async function saveData() {
    if (formData.value.id) {
      await apis.updateForm(formData.value);
    } else {
      await apis.addForm(formData.value);
    }
    formVisible.value = false;
  }
  async function deleteData(id, name = '') {
    const confirmDia = DialogPlugin({
      header: '提示',
      body: name ? `是否删除【${name}】？` : '是否删除该条数据?',
      confirmBtn: '确认',
      cancelBtn: '取消',
      onConfirm: () => {
        apis.delFunc(id).then(() => {
          loadList();
        })
        confirmDia.hide();
      },
      onClose: () => {
        confirmDia.hide();
      },
    });
    
  }

  return {
    searchForm,
    page,
    tableLoading,
    tableData,
    loadList,
    queryPage,
    reset,
    formVisible,
    formData,
    showForm,
    saveData,
    deleteData
  }
}